function wfarray = trainNeuralNetwork(warray, epoch)
% TRAINNEURALNETWORK
%   Esta funcin entrena una red neuronal con un set dado de patrones (X),
%   un vector con las matrices de pesos iniciales (wi) y la solucion
%   deseada para cada patron.
%   
%   Input:
%       X:  Set de patrones
%       wi: Vector de matrices de pesos iniciales para cada capa
%       b:  Solucion deseada para cada patron
%       tol: Tolerancia del error
%       epoch: Cantidad de epocas
%
%   Output:
%       wf: Vector de matrices de pesos de la red ya entrenada

    global ETA A_ETA_ADAP B_ETA_ADAP LAYERS;
    global patterns solutions;
    X = patterns;
    b = solutions;

    wi{1} = reshape( warray(1:60) , 20 , 3 );
    wi{2} = reshape( warray(61:480) , 20 , 21 );
    wi{3} = reshape( warray(481:501) , 1 , 21 );
    
    
    wf = wi;
    previousError = 0;
    deltaWeights = cell(1,length(LAYERS));
    deltaWeights{1} = zeros(LAYERS(1), 2+1);
    for i = 1:length(LAYERS)-1
       deltaWeights{i+1} = zeros(LAYERS(i+1), LAYERS(i)+1); 
    end
    for t = 1:epoch,
        waux = wf;
        for x = 1:length(X(1,:))
            backPropData = feedForward(X(:,x), wf, b(x));
            data = backpropagation(wf, deltaWeights, backPropData, X(:,x));
            wf = data{1};
            deltaWeights = data{2};
        end
        err = errorFunction(X, wf, b);
        % ETA ADAPTATIVO
        if previousError ~= 0
            if err - previousError < 0
                ETA = ETA + A_ETA_ADAP;
                previousError = err;
            elseif err - previousError > 0
                ETA = ETA - ETA*B_ETA_ADAP;
                wf = waux;
                err = previousError;
            end
        end
        
        if (previousError == 0)
            previousError = err;
        end
        
        %if (mod(t,100) == 0)
            %disp('EPOCH:');
            %disp(t);
            %disp('ETA');
            %disp(ETA);
            %disp('Error: ');
            %disp(err);
        %end
       
        X = shufflePatterns(X, b);
        b = X(length(X(:,1)),:);
        X = X(1:length(X(:,1))-1,:);
        %if(err < tol)
        %    break;
        %end
    end
    
    wfarray = [reshape(wf{1},1,60) reshape(wf{2},1,420) reshape(wf{3},1,21)];
end